﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mail.Model;
using System.Web.Razor;
using System.IO;
using System.CodeDom.Compiler;
using System.Net.Mail;
using Microsoft.CSharp;

namespace Core.Razor.Template
{
    public class RazorMail
    {
        public void EmailServiceRequests()
        {
            var language = new CSharpRazorCodeLanguage();
            var host = new RazorEngineHost(language)
            {
                DefaultBaseClass = "ServiceRequestEmailGeneratorBase",
                DefaultClassName = "ServiceRequestEmailGenerator",
                DefaultNamespace = "CustomerRazorTemplate",
            };
            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("CustomerRazorTemplate");

            // Create a new Razor Template Engine

            RazorTemplateEngine engine =
               new RazorTemplateEngine(host);

            // Generate code for the template
            StreamReader sr = new StreamReader("Email.txt");
            GeneratorResults razorResult = engine.GenerateCode(sr);

            CompilerResults compilerResults = new CSharpCodeProvider().CompileAssemblyFromDom(
                new CompilerParameters(new string[] { "CustomerRazorTemplate.exe" })
                , razorResult.GeneratedCode
                );

            // Generate a dynamic class template 
            // instance from the compiled code
            var emailGenerator = (ServiceRequestEmailGeneratorBase)
                compilerResults.CompiledAssembly
                    .CreateInstance(
                  "CustomerRazorTemplate.ServiceRequestEmailGenerator");

            //var emailGenerator = (ServiceRequestEmailGeneratorBase)Activator.CreateInstance(Type.GetType("CustomerRazorTemplate.ServiceRequestEmailGenerator"));
            // Supply any required properties
            emailGenerator.From = "calixhu@gmail.com";

            // Execute the template for each email model
            // and send the email to the customer
            SmtpClient smtp = new SmtpClient();
            var email = emailGenerator.GenerateMailMessage(new EmailCategory());
            smtp.Send(email);
        }
    }
}
